package org.rcy.framework.data.service;

import org.rcy.framework.api.entity.BaseEntity;
import org.rcy.framework.data.dao.BaseDao;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Method;

public abstract class BaseCrudService<T extends BaseEntity> extends AbstractCrudService<T, Long> {

	protected BaseDao<T> dao;


	@Autowired
	public void setDao(BaseDao<T> dao) {
		this.dao = dao;
		super.mapper = dao;
	}

	@Override
	public <S extends T> S save(S entity) {
		if (entity.getId() == null) {
			super.create(entity);
		} else {
			dao.updateByPrimaryKey(entity);
		}
		return entity;
	}

	/**
	 * 失效缓存。需要子类复写。
	 *
	 * @param entity
	 */
	@Override
	protected void evictCache(T entity) {

	}

	/**
	 * 是否使用了缓存, 子类可改写。默认不使用。
	 *
	 * @return
	 */
	@Override
	protected boolean useCache() {
		return false;
	}

	public T selectOne(T entity) {
		return super.findOne(entity).orElse(null);
	}

	public boolean updateSelective(T entity) {
		return dao.updateByPrimaryKeySelective(entity) > 0;
	}

	/**
	 * 查找Dao代理接口类上定义的方法
	 * @param methodName
	 * @return
	 * @throws Exception
	 */
	private Method  findMethod(String methodName) throws Exception {
		Class<?>[] interfaces = dao.getClass().getInterfaces();
		for(Class<?> iface :interfaces) {
			if(BaseDao.class.isAssignableFrom(iface)) {
				Method[] methods = iface.getMethods();
				for(Method method:methods) {
					if(methodName.equals(method.getName())) {
						return method;
					}
				}
			}
		}
		return null;
	}
}
